var Sky = function(id,impressions){
	$sky = $("#"+id);
	var batch= 0;
	var count = 0;
	function createBoll(){
		if(count==impressions.length-1){
			count=0;
		}
                if(impressions[count]!=null)
               {
		var message = impressions[count];
		var type="middle";
		if(message.length>20 && message.length<=30){
			type="big";
		}else if(message.length>15 && message.length<=20){
			type="middle2";
		}else if(message.length>0 && message.length<=5){
			type="small";
		}
		BalloonFactory.getInstances(type,$sky,message);	
		batch++;
		count++;
		if(batch!=5){
			setTimeout(function(){
				createBoll();
			},2000);		
			batch==0;
		}else{
			setTimeout(function(){
				createBoll();
			},8000);	
		}}
	}
	createBoll();
}

var BalloonFactory = {
	getInstances:function(type,apply,message){
		var balloon = new Balloon({type:type,id:this.getid(),message:message});
		balloon.apply(apply);
		balloon.start();
	},
	getid:function(){
		if(!this.id) this.id=0;
		this.id++;
		return "balloon"+this.id;
	}
}

var Balloon = function(conf){
	this.id = conf.id;
	var htmlStr = [];
	this.state = true;
	this.type = conf.type;
	htmlStr[0]='<div class="balloon ';
	htmlStr[1]=conf.type;
	htmlStr[2]='" id="';
	htmlStr[3]=conf.id;
	htmlStr[4]='"><div class="top">';
	htmlStr[5]='<div class="left"><div class="right"><div class="middle">';
	htmlStr[6]=conf.message;
	htmlStr[7]='</div>';
	htmlStr[8]='</div></div></div>';
	htmlStr[9]='<div class="bottom"></div></div>';
	this.html = htmlStr.join("");
}


Balloon.prototype={
	start:function(){
		if(!this.state){
			return;
		}
		var temp = this;
		var top = this.$ballObj.css("top");
		top = parseInt(top);
		if(isNaN(top)){
			top = this.$ballObj.offset().top;
		}
		top-=15;
		
		if(top<=-(this.$ballObj.height())){
			this.$ballObj.remove();
			return;
			top=387;
			var left = parseInt(Math.random()*500+1);
			this.$ballObj.css("left",left+"px");			
		}
		top = parseInt(top);
		this.$ballObj.css("top",top+"px");
		var time = 500;
		
		if(this.type=="middle2"){
			time=400;
		}else if(this.type=="middle"){
			time=200;
		}else if(this.type="small"){
			time=100;
		}
		var time = parseInt(Math.random()*(time-time/2+1)+time/2+1);
			
		setTimeout(function(){
			temp.start();
		},time);
	},
	apply:function($parent){
		$parent.append(this.html);
		this.$ballObj = $("#"+this.id);
		var left = parseInt(Math.random()*500+1);
		this.$ballObj.css("left",left+"px");			
		this.$ballObj.click(function(){
			var t  = $(this);
			var zindex = t.css("zIndex");
			if(zindex=="auto"){
				zindex=0;
			}
			t.css("zIndex",(++zindex)+"");
		});
	}
}
